package transaction_demo;

import transaction_demo.Util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * 3.有事务，被动失败（重启服务器) -- 保持一致性
 * @author haomin
 * @date 2022/04/08 20:50
 **/
public class Demo3 {
    public static void main(String[] args) throws SQLException {
        String sql1 = "insert into records (rid,bid) values (2,2)";
        String sql2 = "update books set stock = stock - 1 where bid = 2";

        try(Connection c = DBUtil.connection()){
            c.setAutoCommit(false);

            try (PreparedStatement ps = c.prepareStatement(sql1)) {
                ps.executeUpdate();
            }

            // 执行完第一条 SQL 之后，要让第二条 SQL 执行失败

            try (PreparedStatement ps = c.prepareStatement(sql2)) {
                ps.executeUpdate();
            }

            c.commit();
        }
    }
}